import Inula, { useState, useEffect } from 'openinula';
import { useHistory, Link, useLocation } from 'inula-router';
import {
  AppstoreOutlined,
  ContainerOutlined,
  DesktopOutlined,
  PieChartOutlined,
} from '@ant-design/icons';
import { Menu } from 'antd';
import '@/style/component/navbar.scss'

function getItem(label, key, icon, children, type) {

  return {
    key,
    icon,
    children,
    label,
    type,
  };
}
const items = [
  getItem(<Link to='/app/one'>应用1</Link>, '1', <PieChartOutlined />),
  getItem(<Link to='/app/two'>应用2</Link>, '2', <DesktopOutlined />),
  getItem(<Link to='/app/three'>应用3</Link>, '3', <ContainerOutlined />),
  getItem('配置应用', 'set', <AppstoreOutlined />, [
    getItem(<Link to='/set/android'>Android</Link>, 'Android'),
    getItem(<Link to='/set/app'>APP</Link>, 'APP'),
  ]),
];

const MenuStyle = {
  height: "calc(100vh - 120px)"
}
const rootSubmenuKeys = ['set'];

export default function NavBar() {
  const history = useHistory();
  const location = useLocation();
  const [openKeys, setOpenKeys] = useState(['set']);
  const [selectedKeys, setSelectedKeys] = useState('1');
  const onOpenChange = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);
    if (latestOpenKey && rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  };
  useEffect(() => {
    const pathname = location.pathname;
    let selectedKey = '1';
    switch (pathname) {
      case '/app/one': { selectedKey = '1'; break; }
      case '/app/two': { selectedKey = '2'; break; }
      case '/app/three': { selectedKey = '3'; break; }
      case '/set/android': { selectedKey = 'Android'; break; }
      case '/set/app': { selectedKey = 'APP'; break; }
      default: { selectedKey = '1'; }
    }
    setSelectedKeys(selectedKey)
  }, [location])

  return <div
    style={{
      width: 256,
      height: 'calc(100vh - 120px)'
    }}
  >
    <Menu
      className='menu'
      style={MenuStyle}
      selectedKeys={selectedKeys}
      openKeys={openKeys}
      onOpenChange={onOpenChange}
      mode="inline"
      items={items}
    />
  </div>
}